<template>
  <el-dialog
    v-model="editDialogVisible"
    title="编辑用户"
    width="60%"
    center
    @close="closeEditDialog(false)"
  >
    <el-form
      :rules="rules"
      :model="form"
      label-width="100px"
      ref="validateForm"
    >
      <el-form-item label="用户名" prop="user_name">
        <el-input v-model="form.user_name" />
      </el-form-item>
      <el-form-item label="用户密码" prop="user_password">
        <el-input v-model="form.user_password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- 这里不要使用默认的,默认的close不是响应式的 -->
        <el-button
          @click="
            () => {
              closeEditDialog(false)
            }
          "
        >
          取消
        </el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, toRefs, ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
//2.根据商品ID查询要编辑的商品数据的方法
function useLoadEditData(state) {
  //console.log('文章Id', state.ArticleId)
  axios.get(`/blog/${state.UserId}`).then((res) => {
    // console.log(res.data.result.data)
    state.form = res.data.result.data
  })
}
//提交编辑好的文章
function useEditData(state, validateForm, emit) {
  const submitEdit = () => {
    //验证表单的值都填完没有
    validateForm.value.validate((valid) => {
      //console.log(valid) //如果有没填的就是false,都填了就是true
      //获取表单数据
      //console.log(state.UserId)
      if (valid) {
        const obj = {
          user_name: state.form.user_name,
          user_password: state.form.user_password,
        }
        //console.log('数据', obj)
        axios.put(`/blog/${state.UserId}`, obj).then((res) => {
          console.log(res)
          // // 关闭表单
          emit('onCloseEditDialog', false, res.data)
        })
      }
    })
  }
  return {
    submitEdit,
  }
}
//
export default {
  props: {
    editDialogVisible: Boolean,
    UserId: Number,
  },
  emits: ['onCloseEditDialog'],
  setup(props, { emit }) {
    const validateForm = ref()
    const state = reactive({
      editDialogVisible: props.editDialogVisible,
      UserId: props.UserId,
      form: {
        user_name: '',
        user_password: '',
      },
    })

    const closeEditDialog = (visible) => {
      // 使用父组件的方法,方法名,传递的参数
      emit('onCloseEditDialog', visible)
    }
    // 校验规则
    const rules = {
      user_name: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
      ],
      user_password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
      ],
    }

    // 接收要打印的文章编号ac
    onMounted(() => {
      //console.log('用户Id', state.UserId)
      //1.挂载的时候,根据用户ID查询要编辑的商品数据
      useLoadEditData(state)
    })
    return {
      ...toRefs(state),
      ...useEditData(state, validateForm, emit),
      closeEditDialog,
      rules,
      validateForm,
    }
  },
}
</script>

<style></style>
